package org.rambadger.command.axon;

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.yammer.metrics.core.HealthCheck;

/**
 * Used by DropWizard to periodically check whether we can connect to the database.
 */
public class MongoHealthCheck extends HealthCheck {
    private final MongoClient mongo;
    private static final String CHECK_NAME = "mongodb connection";

    /**
     * Creates a new MongoHealthCheck instance around the provided {@link MongoClient} instance.
     *
     * @param mongo the MongoClient instance
     */
    public MongoHealthCheck(MongoClient mongo) {
        super(CHECK_NAME);
        this.mongo = mongo;
    }

    @Override
    protected Result check() throws Exception {
        try {
            /*
            Technique based on https://groups.google.com/d/msg/mongodb-user/6egdzjDJnFc/BMeiDJU9cdoJ
            An exception should be thrown if it can't access any of the configured databases
             */
            mongo.getDatabaseNames();
        } catch (MongoException e) {
            return Result.unhealthy(e);
        }
        return Result.healthy();
    }
}
